package com.zrb.mobile.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.model.BaseDto;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;
import com.zrb.mobile.utility.ZrbRestClient.HttpResponseListener;

import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;

public abstract class ABaseRefreshFragment<T extends BaseDto>  extends ABaseFragment implements  AdapterView.OnItemClickListener   {

	
	private ABaseAdapter<T> mAdapter;
	
	
	ABaseAdapter<T> getABaseAdapter() {
		return mAdapter;
	}
	
	public enum RefreshMode {
		/**
		 * 重设数据
		 */
		reset,
		/**
		 * 拉取更多
		 */
		loadmore,
		/**
		 * 刷新最新
		 */
		refresh
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/*ArrayList<T> datas = savedInstanceState == null ? new ArrayList<T>()
                                                        : (ArrayList<T>) savedInstanceState.getSerializable(SAVED_DATAS);*/
		
		ArrayList<T> datas = new ArrayList<T>();
		mAdapter = new MyBaseAdapter(datas, getActivity());
		
/*		if (savedInstanceState != null && savedInstanceState.getSerializable(SAVED_PAGING) != null) {
            mPaging = (IPaging) savedInstanceState.getSerializable(SAVED_PAGING);
		} else {
            mPaging = configPaging();
		}*/
	}
	
 
	
	@SuppressLint("NewApi")
	@Override
	void _layoutInit(LayoutInflater inflater, Bundle savedInstanceSate) {
		super._layoutInit(inflater, savedInstanceSate);
		
		if (getRefreshView() != null) {
		/*	getRefreshView().setOnScrollListener(this);
			getRefreshView().setRecyclerListener(this);*/
			
			//getRefreshView().setOnRefreshListener(this);
            getRefreshView().setOnItemClickListener(this);
		}
 
        getRefreshView().setAdapter(getAdapter());//.setAdapter(getAdapter());
		
       // onChangedByConfig(refreshConfig);
	}
 
	
	public BaseAdapter getAdapter() {
	/*	if (swingAnimAdapter != null)
			return swingAnimAdapter;*/
		
		return mAdapter;
	}
	
	
	public void notifyDataSetChanged() {
 			mAdapter.notifyDataSetChanged();
 	}
	
	public ArrayList<T> getAdapterItems() {
		return mAdapter.getDatas();
	}
	
	private int getAdapterCount() {
  		return mAdapter.getCount();
	}

	public void setAdapterItems(ArrayList<T> items) {
		mAdapter.setDatas(items);
	}
 	
	public void addItems(List<T> items,boolean isAppend) {
 		if(!isAppend) getAdapterItems().clear();
		mAdapter.addItems(items);
	}
	
	public T getLastItem(){
 		return getAdapterItems().get(getAdapterCount()-1);
	}
	
 
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

	}
	
	
	
	abstract protected ABaseAdapter.AbstractItemView<T> newItemView();
	
	abstract public AbsListView getRefreshView();
	//abstract public PullToRefreshListViewEx getRefreshView();
	
	class MyBaseAdapter extends ABaseAdapter<T> {

        public MyBaseAdapter(ArrayList<T> datas, Activity context) {
			super(datas, context);
		}

		@Override
		protected AbstractItemView<T> newItemView() {
			return ABaseRefreshFragment.this.newItemView();
		}

	}
	
	abstract public void onRefreshViewComplete();
	
	abstract public void onHandlerResult(String resStr,RefreshMode curMode);
	
	
	RefreshMode mode;
	ZrbRestClient mZrbRestClient;// final Class<T> responseCls
	public  void LoadData(String urlParams,RefreshMode curMode,final TypeToken<List<T>> responseCls) {
		mode=curMode;
		if(null==mZrbRestClient){
			mZrbRestClient=new ZrbRestClient(this.getActivity());
			mZrbRestClient.setOnhttpResponseListener(new HttpResponseListener() {
				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {

					CommonUtil.showToast(arg0,ABaseRefreshFragment.this.getActivity());
					onRefreshViewComplete();
				   if (mode==RefreshMode.loadmore){}
					   //getRefreshView().hideloading();
					else{}
						//getRefreshView().onRefreshComplete(); 
 				}

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
					// loadingview.Hide();
					String results = new String(arg2);
  					onRefreshViewComplete();
 				    if (mode==RefreshMode.loadmore){}
 						  // getRefreshView().hideloading();
 						else{}
 						//	getRefreshView().onRefreshComplete();
					try {
						JSONObject jsonObject2 = new JSONObject(results);
						int retCode= jsonObject2.getInt("res");
						
 	 				    if(retCode==1){
	 				    	
	 				    //	onHandlerResult(jsonObject2.getString("data"),mode);
	 				    	Gson gson = new Gson(); 
	 				    	List<T> tmpdatas=gson.fromJson(jsonObject2.getString("data"), responseCls.getType());
	  				    	int size=CommonUtil.getSize(tmpdatas);
	 						if(size>0){  
	 				 			addItems(tmpdatas,mode==RefreshMode.loadmore) ;
	 				  		    notifyDataSetChanged();
	 						} 
	 						else {
	 								CommonUtil.showToast(String.format("暂无%1$s信息~~", mode==RefreshMode.refresh? "": "更多") );
	 						}
 						} else
							CommonUtil.showToast(jsonObject2.getString("msg"));
					} catch (Exception e) {
						CommonUtil.showToast(R.string.error_serverdata_loadfail,ABaseRefreshFragment.this.getActivity());
						 
					}
				}
			});
 		}
		mZrbRestClient.getcheckSession(urlParams);
	}

 

}
